#include "BlockQueue.hpp"
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include "Task.hpp"
#include <ctime>

using namespace std;
void *Producer(void *args)
{
    // 生产产品
    // int date = 1;
    BlockQueue<Task> *blockqueue = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        int len = opnums.size();
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char op = opnums[rand() % len];
        Task t(data1, data2, op);
        blockqueue->push(t);
        cout << "产生一个任务: " << t.GetTask() << endl;
        // date++;
        sleep(1);
    }

    return NULL;
}
void *Consumer(void *args)
{
    // 消费
    BlockQueue<Task> *blockqueue = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        Task t = blockqueue->pop();
        t.run();
        cout << "完成一个任务: " << t.GetTask() << "，运算结果为:" << t.GetResult() << endl;
    }

    return NULL;
}
int main()
{
    pthread_t pid[3], cid[5];

    BlockQueue<Task> *blockqueue = new BlockQueue<Task>();
    for (int i = 0; i < 3; i++)
    {
        pthread_create(pid + i, NULL, Producer, blockqueue);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_create(cid + i, NULL, Consumer, blockqueue);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(pid[i], NULL);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(cid[i], NULL);
    }

    delete blockqueue;
}